<!--
 * @Author: your name
 * @Date: 2023-02-28 10:09:47
 * @LastEditTime: 2023-08-16 16:21:50
 * @LastEditors: DESKTOP-4QFD9PO
 * @Description: In User Settings Edit
 * @FilePath: \ClothMes\src\views\WorkshopMaterialReturn\component\WorkshopMaterialReturnDetails.vue
-->

<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow" style="display: inline-block">
        <div>
          <a-form
            size="small"
            :model="pageData"
            layout="inline"
            label-align="right"
            :label-col-props="{ span: 8 }"
            :wrapper-col-props="{ span: 16 }"
          >
            <a-form-item label="织布单号">
              <a-input
                class="bacClass"
                v-model="pageData.planOrderCode"
                @press-enter="huiche"
                allow-clear
                style="width: 200px"
              />
            </a-form-item>

            <a-form-item label="客户">
              <a-input
                class="bacClass"
                v-model="pageData.customName"
                @press-enter="huiche"
                allow-clear
                style="width: 200px"
              />
            </a-form-item>

            <a-form-item label="原料编号">
              <a-input
                class="bacClass"
                v-model="pageData.rawmaterialCode"
                @press-enter="huiche"
                allow-clear
                style="width: 200px"
              />
            </a-form-item>

            <a-form-item label="原料名称">
              <a-input
                class="bacClass"
                v-model="pageData.rawmaterialName"
                @press-enter="huiche"
                allow-clear
                style="width: 200px"
              />
            </a-form-item>

            <a-form-item label="纱批">
              <a-input
                class="bacClass"
                v-model="pageData.yarnBatch"
                @press-enter="huiche"
                allow-clear
                style="width: 200px"
              />
            </a-form-item>

            <a-form-item label="日期" label-col-flex="66px">
              <a-date-picker
                popup-container="html"
                :style="{ width: '228px' }"
                class="bacClass"
                v-model="pageData.dateStart"
              />
            </a-form-item>
            <a-form-item label="至" label-col-flex="38px">
              <a-date-picker
                popup-container="html"
                :style="{ width: '214px' }"
                class="bacClass"
                v-model="pageData.dateEnd"
              />
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar
          :items="pageData.btnList"
          @select="selectHandler"
          @cjtld="cjtlds"
          @del="deleteHandler"
        >
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <!-- <a-space style="float: right; z-index: 9999"> </a-space> -->
      <!-- <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999"> -->
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        @columnVisible="onColumnVisible"
        @columnResized="onColumnResized"
        @columnMoved="onColumnMoved"
        style="height: calc(100% - 45px)"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc1"
        :localeText="localeText1"
      >
      </AgGridVuesCopys>
      <paginationCopys
        :total="total"
        show-total
        show-jumper
        show-page-size
        @change="PageSize"
        @page-size-change="change1"
        style="justify-content: center"
        :page-size="pagination.pageSize"
        :current="pagination.page"
        :page-size-options="pagingList1"
      />
      <!-- </a-spin> -->
    </template>

    <a-drawer
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
      cancel-text="关闭"
      ok-text="保存"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label-col-flex="80px" label="整件件数">
            <a-input-number class="bacClass" v-model="dataForm.pieceNum" :precision="2" />
          </a-form-item>
          <a-form-item label-col-flex="80px" label="散件件数">
            <a-input-number class="bacClass" v-model="dataForm.bulkNum" :precision="2" />
          </a-form-item>
          <a-form-item label-col-flex="80px" label="散件散重">
            <a-input class="bacClass" v-model="dataForm.bulkWeight" :precision="2" />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import QrcodeVue from 'qrcode.vue'
  import ModalDialog from '@/components/ModalDialog.vue'
  import { ref, reactive, onMounted, onActivated } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { ModalDialogType } from '@/types/components'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import WHService, { Warhouse, CompanyList, WhTypeField } from '@/service/wh'
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  interface ClothInfo {
    id: any
    pieceNum: any
    bulkNum: any
    bulkWeight: any
  }

  export default {
    name: 'WorkshopMaterialReturnSummary',
    setup() {
      const dataForm = reactive<ClothInfo>({
        id: null,
        pieceNum: null,
        bulkNum: null,
        bulkWeight: null,
      })
      const headerShow = ref<boolean>(true)
      const total = ref(10)
      const page = ref(1)
      const size = ref(10)
      function PageSize(val: any) {
        pagination.page = val
        doRefresh()
      }

      function change1(val: any) {
        pagination.pageSize = val
        doRefresh()
      }
      let id = ref(1)
      //查询

      function doRefresh() {
        pageData.pageLoading = true
        updateGridState01()
        post({
          url: '/qms/MaterialReturn/getPage',
          data: {
            page: pagination.page,
            size: pagination.pageSize,
            deleteState: 0,

            planOrderCode: pageData.planOrderCode,
            customName: pageData.customName,
            rawmaterialCode: pageData.rawmaterialCode,
            rawmaterialName: pageData.rawmaterialName,
            yarnBatch: pageData.yarnBatch,
            beginDate: pageData.dateStart,
            endDate: pageData.dateEnd,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              gridOption.value.setRowData(data.list)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      const huiche = () => {
        doRefresh()
      }
      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const selectedRowKeysChecked = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const tableColumns = useTableColumn([
        {
          title: '织布单号',
          key: 'planOrderCode',
          dataIndex: 'planOrderCode',
          width: 150,
        },
        {
          title: '客户',
          key: 'customName',
          dataIndex: 'customName',
          width: 150,
        },
        {
          title: '机台号',
          key: 'machineCode',
          dataIndex: 'machineCode',
          width: 150,
        },
        {
          title: '原料编号',
          key: 'rawmaterialCode',
          dataIndex: 'rawmaterialCode',
          width: 150,
        },
        {
          title: '原料名称',
          key: 'rawmaterialName',
          dataIndex: 'rawmaterialName',
          width: 150,
        },
        {
          title: '公司',
          key: 'outSouringCompany',
          dataIndex: 'outSouringCompany',
          width: 150,
        },
        {
          title: '纱牌',
          key: 'yarnCard',
          dataIndex: 'yarnCard',
          width: 150,
        },
        {
          title: '色号',
          key: 'colorCode',
          dataIndex: 'colorCode',
          width: 150,
        },
        {
          title: '色称',
          key: 'colorName',
          dataIndex: 'colorName',
          width: 150,
        },
        {
          title: '整件/个数',
          key: 'pieceCount',
          dataIndex: 'pieceCount',
          width: 150,
        },
        {
          title: '散件/个数',
          key: 'bulkCount',
          dataIndex: 'bulkCount',
          width: 150,
        },
        {
          title: '纱批',
          key: 'yarnBatch',
          dataIndex: 'yarnBatch',
          width: 150,
        },

        {
          title: '等级',
          key: 'grade',
          dataIndex: 'grade',
          width: 150,
        },

        // {
        //   title: '理论余料数量',
        //   key: 'brandName',
        //   dataIndex: 'brandName',
        //   width: 150,
        // },

        {
          title: '实际余料重量',
          key: 'weight',
          dataIndex: 'weight',
          width: 200,
        },
        {
          title: '整件件数',
          key: 'pieceNum',
          dataIndex: 'pieceNum',
          width: 200,
        },

        {
          title: '整件件重',
          key: 'pieceWeight',
          dataIndex: 'pieceWeight',
          width: 200,
        },
        {
          title: '散件件数',
          key: 'bulkNum',
          dataIndex: 'bulkNum',
          width: 200,
        },
        {
          title: '散件散重',
          key: 'bulkWeight',
          dataIndex: 'bulkWeight',
          width: 200,
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 200,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '操作',
          key: 'act',
          slotName: 'act',
          width: 80,
          fixed: 'right',
        },
      ])
      //获取公司部门组列表
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }

      let tc1: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        if (o.slotName === 'act') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 80
          obj['cellRenderer'] = {
            template: `<a-space><el-button style="color:#165dff;" @click="a" class="gesture" link v-if="f">修改</el-button></a-space>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              let f = permissionStore.hasPermisson('cjtlmx.xg')
              return {
                a,
                ainfo: props.params.data,
                f,
              }
            },
          }
        }
        return obj
      })
      let a1 = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc1 = a1.concat(tc1)

      const pageData = reactive<{
        pageLoading: boolean
        customName: any
        rawmaterialCode: any
        rawmaterialName: any
        yarnBatch: any
        dateStart: any
        dateEnd: any
        planOrderCode: any
        showAdd: boolean
        sideTitle: string
        btnList: any[]
      }>({
        sideTitle: '修改',
        showAdd: false,
        pageLoading: false,
        planOrderCode: '',
        customName: '',
        rawmaterialCode: '',
        rawmaterialName: '',
        yarnBatch: '',
        dateStart: '',
        dateEnd: '',
        btnList: [],
      })

      onMounted(() => {
        // doRefresh();
        updateGridState01()
      })
      let isIDs: any = ref(1)

      // 未处理分页查询
      const selectHandler = () => {
        pagination.page = 1
        loadings.value = true

        doRefresh()
      }

      let loadings = ref(false)

      // 一表格准备事件
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }

      const whList = ref<any[]>([])
      const whService = new WHService()
      const whTypeList = whService.whTypeList
      const whTypeFieldList = whService.whTypeFieldList
      const companyList: any = whService.companyList

      // 一表生成拆纱单
      const cjtlds = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          // console.log(gridOption.value.getSelectedRows());

          Message.error('请先勾选')
          return
        }
        let list = gridOption.value.getSelectedRows()
        let flag = false
        for (let i = 1; i < list.length; i++) {
          if (list[0]['planOrderCode'] != list[i]['planOrderCode']) {
            flag = true
          }
          if (flag) {
            Message.error({
              content: '勾选的织布单号要一致',
              duration: 5000,
            })
            return
          }
          // if (list[0]['batch'] != list[i]['batch']) {
          //     flag = true
          // }
          // if (flag) {
          //     Message.error({
          //         content: "勾选的批次不能不同",
          //         duration: 5000,
          //     });
          //     return
          // }
          // if (list[0]['colorCode'] != list[i]['colorCode']) {
          //     flag = true
          // }
          // if (flag) {
          //     Message.error({
          //         content: "勾选的色号不能不同",
          //         duration: 5000,
          //     });
          //     return
          // }
          // if (list[0]['colorName'] != list[i]['colorName']) {
          //     flag = true
          // }
          // if (flag) {
          //     Message.error({
          //         content: "勾选的色称不能不同",
          //         duration: 5000,
          //     });
          //     return
          // }
        }
        Modal.confirm({
          title: '系统提示',
          content: '是否生成退料单?',
          onOk() {
            post({
              url: '/qms/MaterialReturnGather/insert',
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            }).then(({ code, data, message }: any) => {
              if (code === 200) {
                Message.success({
                  content: '创建成功',
                  duration: 5000,
                })

                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: message,
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            post({
              url: '/qms/MaterialReturn/delete',
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            }).then(({ code, data, message }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '删除失败',
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      const editHandler = (record: any) => {
        for (var key in record) {
          dataForm[key] = record[key]
        }
        pageData.showAdd = true
      }
      const formRef = ref<FormInstance>()
      const sideOk = () => {
        post({
          url: '/qms/MaterialReturn/update',
          data: [dataForm],
        }).then((res: any) => {
          if (res.code === 200) {
            formRef.value?.resetFields()
            pageData.showAdd = false

            Message.success({
              content: '修改成功',
              duration: 5000,
            })
            doRefresh()
          } else {
            Message.error({
              content: res.message,
              duration: 5000,
            })
          }
        })
      }
      const scrollbar = ref(true)
      let visiblecg = ref(false)
      let visiblecg1 = ref(false)
      let visiblecg2 = ref(false)
      let visiblecg3 = ref(false)
      let visiblecg5 = ref(false)
      let visiblecg6 = ref(false)
      let qrModal = ref<ModalDialogType | null>(null)
      let idDtaDy: any = ref({
        printNum: '',
      })
      let idDtaDys: any = ref({})
      let idDtaDys1: any = ref({})
      let idDtaDyss: any = ref([{}])

      const pagingList1: any = ref(pagingList)
      const localeText1: any = ref(localeText)
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()

      if (permissionStore.hasPermisson('cjtlmx.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('cjtlmx.cjtld')) {
        pageData.btnList.push('创建退料单')
      }
      if (permissionStore.hasPermisson('cjtlmx.sc')) {
        pageData.btnList.push('删除')
      }
      const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
        saveOrUpdateGridState01('WorkshopMaterialReturnDetails-1', gridOption, colState, tc1)
      const onColumnMoved = () => {
        saveGridState01()
      }
      const onColumnResized = () => {
        saveGridState01()
      }
      const onColumnVisible = () => {
        saveGridState01()
      }
      return {
        saveOrUpdateGridState01,
        saveGridState01,
        updateGridState01,
        onColumnMoved,
        onColumnResized,
        onColumnVisible,
        colState,
        pagingList1,
        localeText1,
        idDtaDys1,
        idDtaDyss,
        visiblecg1,
        visiblecg2,
        visiblecg3,
        visiblecg5,
        visiblecg6,
        scrollbar,
        huiche,
        idDtaDy,
        idDtaDys,
        qrModal,

        print,

        cjtlds,
        whTypeList,

        isIDs,
        companyList,

        whList,

        id,

        tc1,

        gridOption,
        sideOk,
        gridReady,
        editHandler,
        total,
        dataForm,
        selectedRowKeys,
        s: selectedRowKeysChecked.selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        selectHandler,
        defaultColDef,
        deleteHandler,
        visiblecg,
        headerShow,
        change1,
        PageSize,
      }
    },
    components: { Toolbar, PageTabelLayout,  ModalDialog, QrcodeVue },
  }
</script>
<style scoped lang="less">
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
</style>
